package com.metacube.questionbank.controller;


import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.metacube.questionbank.dto.QuestionDTO;
import com.metacube.questionbank.service.Utility;
import com.metacube.questionbank.service.Validator;


@Controller
@RequestMapping("/question")	//url pattern
public class QuestionController {
	
	@Autowired
	Validator validate;
	
	@Autowired
	Utility utility;
	
	@RequestMapping(value = "/postQuestion",  method = RequestMethod.POST)
	public ModelAndView postQuestion(@ModelAttribute QuestionDTO qDTO, HttpSession session) {
		
		String id = (String) session.getAttribute("sessionId");
		
		int userId = Integer.parseInt(id);
		
		qDTO.setqTag("JAVA");
		
		if(validate.checkQuestion(qDTO)) {
			
			return new ModelAndView("postQuestion.jsp","errorMessage", "Title and Tag Can't be empty");
			
		} else {
			
			if (utility.initQuestion(qDTO, userId)) {
				
				ModelAndView model = new ModelAndView("postAnswer.jsp");
				
				model.addObject("qDTO", qDTO);

				return model;
				
			} else {
				
				return new ModelAndView("postQuestion.jsp","errorMessage","Your question not valid");		
			}
			
		}
			
	}
	
	@RequestMapping("getQuestionForAnswer")
	public ModelAndView getQuestionForAnswer(HttpServletRequest request) {
		
		String quesId = (String)request.getParameter("qId");
		
		int qId = Integer.parseInt(quesId);
		
		List<QuestionDTO> quesList = utility.getQuestionForAnswer(qId);
		
		ModelAndView model = new ModelAndView("postAnswer.jsp");
		
		model.addObject("quesList",quesList);
		
		return model;	
	}
	
	
	@RequestMapping(value="myQuestions")
	@ResponseBody
	public List<QuestionDTO> getMyQuestions(HttpSession session){
		
		int userId=(int) session.getAttribute("sessionId");
		
		return utility.getMyQuestions(userId);	
	}
	
	@RequestMapping(value="recentQuestions")
	@ResponseBody
	public List<QuestionDTO> getRecentQuestions(HttpSession session){
		
		return utility.getRecentQuestions();	
	}
	
	
	@RequestMapping(value="unansweredQuestions")
	@ResponseBody
	public List<QuestionDTO> unansweredQuestions(HttpSession session){
		
		return utility.getUnansweredQuestions();
	}

}
